import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:openim_common/openim_common.dart';
import 'package:flutter_openim_sdk/flutter_openim_sdk.dart';

import 'chat_history_search_logic.dart';

class ChatHistorySearchPage extends StatelessWidget {
  final logic = Get.find<ChatHistorySearchLogic>();

  ChatHistorySearchPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Styles.c_F8F9FA,
      appBar: _buildAppBar(),
      body: Column(
        children: [
          _buildSearchTypeFilter(),
          Expanded(
            child: Obx(() => _buildSearchContent()),
          ),
        ],
      ),
    );
  }

   // 构建应用栏
  PreferredSizeWidget _buildAppBar() {
    return AppBar(
      backgroundColor: Styles.c_FFFFFF,
      elevation: 0,
      leading: IconButton(
        icon: Icon(Icons.arrow_back, color: Styles.c_0C1C33),
        onPressed: () => Get.back(),
      ),
      title: Container(
        height: 36.h,
        decoration: BoxDecoration(
          color: Styles.c_F8F9FA,
          borderRadius: BorderRadius.circular(18.r),
        ),
        child: TextField(
          controller: logic.searchController,
          focusNode: logic.searchFocusNode,
          autofocus: true,
          decoration: InputDecoration(
            hintText: '搜索聊天记录',
            hintStyle: Styles.ts_8E9AB0_16sp,
            border: InputBorder.none,
            contentPadding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
            suffixIcon: Obx(() => logic.hasSearchText.value
                ? IconButton(
                    icon: Icon(Icons.clear, size: 20.w, color: Styles.c_8E9AB0),
                    onPressed: logic.clearSearch,
                  )
                : SizedBox()),
          ),
          style: Styles.ts_0C1C33_14sp,
          textInputAction: TextInputAction.search,
          onSubmitted: (_) => logic.performSearch(),
        ),
      ),
      actions: [
        TextButton(
          onPressed: logic.performSearch,
          child: Text('搜索', style: Styles.ts_0089FF_16sp),
        ),
      ],
    );
  }

  // 构建搜索类型筛选器
  Widget _buildSearchTypeFilter() {
    return Container(
      height: 44.h,
      color: Styles.c_FFFFFF,
      child: Obx(() => Row(
        children: List.generate(logic.searchTypes.length, (index) {
          final isSelected = logic.selectedSearchType.value == index;
          return Expanded(
            child: GestureDetector(
              onTap: () => logic.changeSearchType(index),
              child: Container(
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  border: Border(
                    bottom: BorderSide(
                      color: isSelected ? Styles.c_0089FF : Colors.transparent,
                      width: 2.h,
                    ),
                  ),
                ),
                child: Text(
                  logic.searchTypes[index],
                  style: isSelected ? Styles.ts_0089FF_16sp : Styles.ts_8E9AB0_16sp,
                ),
              ),
            ),
          );
        }),
      )),
    );
  }

  // 构建搜索内容区域
  Widget _buildSearchContent() {
    // 如果选择了图片或文件类型，且没有搜索过，显示提示信息
    if (!logic.hasSearched.value && (logic.selectedSearchType.value == 2 || logic.selectedSearchType.value == 3)) {
      return _buildMediaTypeEmptyState();
    }
    
    if (!logic.hasSearched.value) {
      return _buildEmptyState();
    }

    if (logic.isSearching.value && logic.searchResults.isEmpty) {
      return _buildLoadingState();
    }

    if (logic.searchResults.isEmpty) {
      return _buildNoResultState();
    }

    return _buildSearchResults();
  }

  // 构建媒体类型的空状态（图片/文件）
  Widget _buildMediaTypeEmptyState() {
    final isImageType = logic.selectedSearchType.value == 2;
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            isImageType ? Icons.image : Icons.insert_drive_file,
            size: 64.w,
            color: Styles.c_8E9AB0,
          ),
          16.verticalSpace,
          Text(
            isImageType ? '点击查看所有图片' : '点击查看所有文件',
            style: Styles.ts_8E9AB0_16sp,
          ),
          8.verticalSpace,
          ElevatedButton(
            onPressed: () => logic.changeSearchType(logic.selectedSearchType.value),
            style: ElevatedButton.styleFrom(
              backgroundColor: Styles.c_0089FF,
              foregroundColor: Colors.white,
            ),
            child: Text(isImageType ? '加载所有图片' : '加载所有文件'),
          ),
        ],
      ),
    );
  }

  // 构建空状态
  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.search,
            size: 64.w,
            color: Styles.c_8E9AB0,
          ),
          16.verticalSpace,
          Text(
            '输入关键词搜索聊天记录',
            style: Styles.ts_8E9AB0_16sp,
          ),
        ],
      ),
    );
  }

  // 构建加载状态
  Widget _buildLoadingState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          CircularProgressIndicator(color: Styles.c_0089FF),
          16.verticalSpace,
          Text('搜索中...', style: Styles.ts_8E9AB0_16sp),
        ],
      ),
    );
  }

  // 构建无结果状态
  Widget _buildNoResultState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.search_off,
            size: 64.w,
            color: Styles.c_8E9AB0,
          ),
          16.verticalSpace,
          Text(
            '未找到相关聊天记录',
            style: Styles.ts_8E9AB0_16sp,
          ),
          8.verticalSpace,
          Text(
            '尝试使用其他关键词',
            style: Styles.ts_8E9AB0_14sp,
          ),
        ],
      ),
    );
  }

  // 构建搜索结果列表
  Widget _buildSearchResults() {
    return ListView.builder(
      padding: EdgeInsets.symmetric(vertical: 8.h),
      itemCount: logic.searchResults.length + (logic.isSearching.value ? 1 : 0),
      itemBuilder: (context, index) {
        if (index == logic.searchResults.length) {
          return _buildLoadingItem();
        }

        final message = logic.searchResults[index];
        return _buildMessageItem(message);
      },
    );
  }

  // 构建加载更多项
  Widget _buildLoadingItem() {
    return Container(
      height: 50.h,
      alignment: Alignment.center,
      child: CircularProgressIndicator(
        color: Styles.c_0089FF,
        strokeWidth: 2.w,
      ),
    );
  }

    // 构建消息项
  Widget _buildMessageItem(Message message) {
    final isFromSelf = message.sendID == OpenIM.iMManager.userID;
    final senderName = isFromSelf ? '我' : (message.senderNickname ?? '');
    final content = logic.getMessageDisplayContent(message);
    final time = logic.formatMessageTime(message.sendTime ?? 0);

    return GestureDetector(
      onTap: () {
        // 如果是图片、视频或文件，直接预览/打开
        if (message.contentType == MessageType.picture || 
            message.contentType == MessageType.video ||
            message.contentType == MessageType.file) {
          IMUtils.parseClickEvent(message);
        } else {
          // 其他类型消息跳转到聊天位置
          logic.jumpToMessage(message);
        }
      },
      child: Container(
        margin: EdgeInsets.symmetric(horizontal: 12.w, vertical: 4.h),
        padding: EdgeInsets.all(12.w),
        decoration: BoxDecoration(
          color: Styles.c_FFFFFF,
          borderRadius: BorderRadius.circular(8.r),
        ),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 用户头像
            GestureDetector(
              onTap: () => logic.openUserProfile(message),
              child: AvatarView(
                width: 40.w,
                height: 40.h,
                url: message.senderFaceUrl,
                text: senderName,
                isCircle: true,
              ),
            ),
            12.horizontalSpace,
            // 消息内容区域
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 发送者和时间
                  Row(
                    children: [
                      Text(
                        senderName,
                        style: Styles.ts_0C1C33_14sp.copyWith(
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                      Spacer(),
                      Text(
                        time,
                        style: Styles.ts_8E9AB0_12sp,
                      ),
                    ],
                  ),
                  8.verticalSpace,
                  // 消息内容
                  if (message.contentType == MessageType.text)
                    RichText(
                      text: TextSpan(
                        children: logic.getHighlightedText(content, logic.searchKeyword.value),
                      ),
                      maxLines: 3,
                      overflow: TextOverflow.ellipsis,
                    )
                  else if (message.contentType == MessageType.picture)
                    // 图片消息显示缩略图
                    _buildImagePreview(message)
                  else if (message.contentType == MessageType.video)
                    // 视频消息显示缩略图
                    _buildVideoPreview(message)
                  else if (message.contentType == MessageType.file)
                    // 文件消息显示文件信息
                    _buildFilePreview(message)
                  else
                    Text(
                      content,
                      style: Styles.ts_8E9AB0_14sp,
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                  // 消息类型图标
                  if (message.contentType != MessageType.text && 
                      message.contentType != MessageType.picture &&
                      message.contentType != MessageType.video &&
                      message.contentType != MessageType.file) ...[
                    4.verticalSpace,
                    Row(
                      children: [
                        _buildMessageTypeIcon(message.contentType!),
                        4.horizontalSpace,
                        Text(
                          _getMessageTypeText(message.contentType!),
                          style: Styles.ts_8E9AB0_12sp,
                        ),
                      ],
                    ),
                  ],
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 构建图片预览
  Widget _buildImagePreview(Message message) {
    final imageUrl = message.pictureElem?.sourcePicture?.url ?? 
                     message.pictureElem?.snapshotPicture?.url ?? '';
    
    return Container(
      width: 120.w,
      height: 80.h,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(8.r),
        color: Styles.c_F8F9FA,
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(8.r),
        child: imageUrl.isNotEmpty
            ? ImageUtil.networkImage(
                url: imageUrl,
                fit: BoxFit.cover,
                width: 120.w,
                height: 80.h,
              )
            : Icon(
                Icons.image,
                size: 40.w,
                color: Styles.c_8E9AB0,
              ),
      ),
    );
  }

  // 构建视频预览
  Widget _buildVideoPreview(Message message) {
    final thumbnailUrl = message.videoElem?.snapshotUrl ?? '';
    
    return Container(
      width: 120.w,
      height: 80.h,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(8.r),
        color: Styles.c_F8F9FA,
      ),
      child: Stack(
        alignment: Alignment.center,
        children: [
          ClipRRect(
            borderRadius: BorderRadius.circular(8.r),
            child: thumbnailUrl.isNotEmpty
                ? ImageUtil.networkImage(
                    url: thumbnailUrl,
                    fit: BoxFit.cover,
                    width: 120.w,
                    height: 80.h,
                  )
                : Container(
                    width: 120.w,
                    height: 80.h,
                    color: Styles.c_8E9AB0.withOpacity(0.3),
                    child: Icon(
                      Icons.videocam,
                      size: 40.w,
                      color: Styles.c_8E9AB0,
                    ),
                  ),
          ),
          // 播放按钮
          Container(
            width: 32.w,
            height: 32.w,
            decoration: BoxDecoration(
              color: Colors.black.withOpacity(0.6),
              shape: BoxShape.circle,
            ),
            child: Icon(
              Icons.play_arrow,
              color: Colors.white,
              size: 20.w,
            ),
          ),
        ],
      ),
    );
  }

  // 构建文件预览
  Widget _buildFilePreview(Message message) {
    final fileName = message.fileElem?.fileName ?? '未知文件';
    final fileSize = message.fileElem?.fileSize ?? 0;
    final fileSizeText = IMUtils.formatBytes(fileSize);
    
    return Container(
      padding: EdgeInsets.all(12.w),
      decoration: BoxDecoration(
        color: Styles.c_F8F9FA,
        borderRadius: BorderRadius.circular(8.r),
        border: Border.all(color: Styles.c_E8EAEF),
      ),
      child: Row(
        children: [
          // 文件图标
          Container(
            width: 40.w,
            height: 40.w,
            decoration: BoxDecoration(
              color: Styles.c_0089FF.withOpacity(0.1),
              borderRadius: BorderRadius.circular(8.r),
            ),
            child: Icon(
              Icons.insert_drive_file,
              color: Styles.c_0089FF,
              size: 24.w,
            ),
          ),
          12.horizontalSpace,
          // 文件信息
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  fileName,
                  style: Styles.ts_0C1C33_14sp.copyWith(
                    fontWeight: FontWeight.w500,
                  ),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
                4.verticalSpace,
                Text(
                  fileSizeText,
                  style: Styles.ts_8E9AB0_12sp,
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // ... existing code ...

  // 构建消息类型图标
  Widget _buildMessageTypeIcon(int messageType) {
    IconData iconData;
    Color iconColor = Styles.c_8E9AB0;

    switch (messageType) {
      case MessageType.picture:
        iconData = Icons.image;
        break;
      case MessageType.video:
        iconData = Icons.videocam;
        break;
      case MessageType.file:
        iconData = Icons.insert_drive_file;
        break;
      case MessageType.voice:
        iconData = Icons.mic;
        break;
      case MessageType.location:
        iconData = Icons.location_on;
        break;
      default:
        iconData = Icons.message;
    }

    return Icon(
      iconData,
      size: 16.w,
      color: iconColor,
    );
  }

  // 获取消息类型文本
  String _getMessageTypeText(int messageType) {
    switch (messageType) {
      case MessageType.picture:
        return '图片';
      case MessageType.video:
        return '视频';
      case MessageType.file:
        return '文件';
      case MessageType.voice:
        return '语音';
      case MessageType.location:
        return '位置';
      default:
        return '消息';
    }
  }
}